﻿/// <reference path="jquery-1.10.2.min.js" />
/// <reference path="knockout-3.0.0.js" />

function ViewModel() {
    var self = this;
    self.contacts = ko.observableArray();//联系人列表
    self.contact = ko.observable();//编辑联系人
    self.addresss = "http://192.168.1.103:8010/api/";
    self.load= function() {
        $.ajax({
            url: self.addresss+ "Contacts",
            type: "Get",
            success: function(data) {
                self.contacts(data);
            }

        });
    }


    self.showDialog = function(data) {
        if (!data.Id) {
            data = { Id: "", Name: "", EmailAddress: "", Address: "" ,PhoneNo: "" };
        }

        self.contact(data);
        $(".modal").modal("show");
    };

    

    //调用Web API添加/修改联系人信息
    self.save = function () {
        $(".modal").modal('hide');
        if (self.contact().Id) {
            $.ajax({
                url: self.addresss + "contacts/" + self.contact().Id,
                type: "PUT",
                data: self.contact(),
                success: function () {
                    self.load();
                }
            });
        }
        else {
            $.ajax({
                url: self.addresss + "contacts",
                type: "POST",
                data: self.contact(),
                success: function () {
                    self.load();
                }
            });
        }
    };

    //删除现有联系人
    self.delete = function (data) {
        $.ajax({
            url: self.addresss + "contacts/" + data.Id,
            type: "DELETE",
            success: function () {
                self.load();
            }
        });
    };

    self.load();

}
$(function() {
    ko.applyBindings(new ViewModel());
})